package com.castle.fortress.admin.cms.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.cms.dto.CmsTemplateDto;
import com.castle.fortress.admin.cms.entity.CmsTemplateEntity;
import com.castle.fortress.admin.cms.service.CmsTemplateService;
import com.castle.fortress.admin.core.config.CastleWebConfig;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.admin.utils.ResourceUtil;
import com.castle.fortress.admin.utils.SpringUtils;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * cms模板管理表 控制器
 *
 * @author castle
 * @since 2022-02-28
 */
@Api(tags="cms模板管理表管理控制器")
@Controller
public class CmsTemplateController {
    @Value("${castle.cms.templatePath}")
    private String templatePath;
    @Autowired
    private CmsTemplateService cmsTemplateService;

    /**
     * cms模板管理表的分页展示
     * @param cmsTemplateDto cms模板管理表实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @ApiOperation("cms模板管理表分页展示")
    @GetMapping("/cms/cmsTemplate/page")
    @ResponseBody
    @RequiresPermissions("cms:cmsTemplate:pageList")
    public RespBody<IPage<CmsTemplateDto>> pageCmsTemplate(CmsTemplateDto cmsTemplateDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<CmsTemplateDto> page = new Page(pageIndex, pageSize);
        cmsTemplateService.sycnTemp();
        IPage<CmsTemplateDto> pages = cmsTemplateService.pageCmsTemplate(page, cmsTemplateDto);

        return RespBody.data(pages);
    }

    /**
     * cms模板文件列表展示
     * @param cmsTemplateDto cms模板管理表实体类
     * @return
     */
    @ApiOperation("cms模板文件列表展示")
    @GetMapping("/cms/cmsTemplate/list")
    @ResponseBody
    @RequiresPermissions("cms:cmsTemplate:refresh")
    public RespBody<Map<String,Object>> listCmsTemplateFiles(CmsTemplateDto cmsTemplateDto){
        if(cmsTemplateDto == null || StrUtil.isEmpty(cmsTemplateDto.getTitle())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        Map<String,Object> map = new HashMap<>();
        String contents="";
        String fileName="";
        List<Map<String,String>>  list =ResourceUtil.getResources(templatePath+cmsTemplateDto.getTitle());
        for(Map<String,String> m:list){
//            m.put("parentPath",m.get("filePath").substring(templatePath.length()+1));
            if(StrUtil.isEmpty(contents) && ResourceUtil.FILE_TYPE.equals(m.get("directoryFlag"))){
                contents = ResourceUtil.getResourceContents(m.get("filePath"));
                fileName=m.get("fileName");
            }
            if("index.html".equals(m.get("fileName"))){
                contents = ResourceUtil.getResourceContents(m.get("filePath"));
                fileName = "index.html";
            }
            //将文件路径清空
            m.put("filePath","");
        }
        map.put("templatePath",templatePath);
        map.put("files",list);
        map.put("contents",contents);
        map.put("fileName",fileName);
        return RespBody.data(map);
    }
    /**
     * 获取文件内容
     * @param cmsTemplateDto cms模板管理表实体类
     * @return
     */
    @ApiOperation("获取模板内容")
    @PostMapping("/cms/cmsTemplate/contents")
    @ResponseBody
    @RequiresPermissions("cms:cmsTemplate:refresh")
    public RespBody<String> cmsFileContents(@RequestBody CmsTemplateDto cmsTemplateDto){
        if(cmsTemplateDto == null || StrUtil.isEmpty(cmsTemplateDto.getTitle()) ||StrUtil.isEmpty(cmsTemplateDto.getFileName())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        String path = templatePath+cmsTemplateDto.getTitle()+(StrUtil.isEmpty(cmsTemplateDto.getDirPath())?"":(cmsTemplateDto.getDirPath()))+"/"+cmsTemplateDto.getFileName();
        String contents=ResourceUtil.getResourceContents(path);
        return RespBody.data(contents);
    }

    /**
     * 保存文件内容
     * @param cmsTemplateDto cms模板管理表实体类
     * @return
     */
    @ApiOperation("保存模板内容")
    @PostMapping("/cms/cmsTemplate/save")
    @ResponseBody
    @RequiresPermissions("cms:cmsTemplate:refresh")
    public RespBody<String> saveCmsTemplate(@RequestBody CmsTemplateDto cmsTemplateDto){
        if(cmsTemplateDto == null || StrUtil.isEmpty(cmsTemplateDto.getTitle()) ||StrUtil.isEmpty(cmsTemplateDto.getFileName())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        String path = templatePath+cmsTemplateDto.getTitle()+(StrUtil.isEmpty(cmsTemplateDto.getDirPath())?"":("/"+cmsTemplateDto.getDirPath()))+"/"+cmsTemplateDto.getFileName();
        ResourceUtil.coverResourceContents(path,cmsTemplateDto.getContents());
        if(YesNoEnum.YES.getCode().equals(cmsTemplateDto.getStatus())){
            CastleWebConfig.update(SpringUtils.getApplicationContext(),templatePath,cmsTemplateDto.getTitle());
        }
        return RespBody.data("保存成功");
    }

    /**
     * cms模板管理表编辑
     * @param cmsTemplateDto cms模板管理表实体类
     * @return
     */
    @ApiOperation("cms模板管理表编辑")
    @PostMapping("/cms/cmsTemplate/edit")
    @ResponseBody
    @RequiresPermissions("cms:cmsTemplate:edit")
    public RespBody<String> updateCmsTemplate(@RequestBody CmsTemplateDto cmsTemplateDto){
        if(cmsTemplateDto == null || cmsTemplateDto.getId() == null || cmsTemplateDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        CmsTemplateEntity cmsTemplateEntity = ConvertUtil.transformObj(cmsTemplateDto,CmsTemplateEntity.class);
        //将其他的模板关闭
        if(YesNoEnum.YES.getCode().equals(cmsTemplateDto.getStatus())){
            cmsTemplateService.closeAll();
        }
        if(cmsTemplateService.updateById(cmsTemplateEntity)){
            CmsTemplateEntity entity = cmsTemplateService.getById(cmsTemplateEntity.getId());
            if(YesNoEnum.YES.getCode().equals(cmsTemplateDto.getStatus())){
                CastleWebConfig.update(SpringUtils.getApplicationContext(),templatePath,entity.getTitle());
            }
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * cms模板管理表删除
     * @param cmsTemplateDto
     * @return
     */
    @ApiOperation("cms模板管理表删除")
    @PostMapping("/cms/cmsTemplate/delete")
    @ResponseBody
    @RequiresPermissions("cms:cmsTemplate:delete")
    public RespBody<String> deleteCmsTemplate(@RequestBody CmsTemplateDto cmsTemplateDto){
        if(cmsTemplateDto == null || StrUtil.isEmpty(cmsTemplateDto.getTitle()) || StrUtil.isEmpty(cmsTemplateDto.getFileName())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        String path= ("/".equals(cmsTemplateDto.getDirPath())||StrUtil.isEmpty(cmsTemplateDto.getDirPath()))?"":cmsTemplateDto.getDirPath() ;
        File targetFile = new File(templatePath+ File.separator+cmsTemplateDto.getTitle()+path+File.separator+cmsTemplateDto.getFileName());
        FileUtil.del(targetFile);
        return RespBody.data("保存成功");
    }


    /**
     * cms模板管理表详情
     * @param id cms模板管理表id
     * @return
     */
    @ApiOperation("cms模板管理表详情")
    @GetMapping("/cms/cmsTemplate/info")
    @ResponseBody
    @RequiresPermissions("cms:cmsTemplate:info")
    public RespBody<CmsTemplateDto> infoCmsTemplate(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        CmsTemplateEntity cmsTemplateEntity = cmsTemplateService.getById(id);
        CmsTemplateDto cmsTemplateDto = ConvertUtil.transformObj(cmsTemplateEntity,CmsTemplateDto.class);

        return RespBody.data(cmsTemplateDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
	@PostMapping("/cms/cmsTemplate/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<CmsTemplateDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<CmsTemplateDto> list = cmsTemplateService.listCmsTemplate(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}

    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation("模板上传")
    @PostMapping("/cms/cmsTemplate/upload")
    @RequiresPermissions("cms:cmsTemplate:refresh")
    public RespBody<String> upload(@RequestParam("tempFile") MultipartFile file, String title,String dirPath){
        if (file.isEmpty() || StrUtil.isEmpty(title)) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        return cmsTemplateService.upload(file,title,dirPath);

    }

    /**
     * cms模板文件过滤列表展示
     * @param type cover 单页 list 列表 article 文章 special 专题 tag 标签
     * @return
     */
    @ApiOperation("cms模板文件过滤列表展示")
    @GetMapping("/cms/cmsTemplate/filter")
    @ResponseBody
    public RespBody<List<Map<String,String>>> filterCmsTemplateFiles(@RequestParam String type){
        if(StrUtil.isEmpty(type)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        CmsTemplateDto dto = cmsTemplateService.getActiveTemp();
        List<Map<String,String>> tList = new ArrayList<>();
        String fileName="";
        List<Map<String,String>>  list =ResourceUtil.getResources(templatePath+dto.getTitle());
        for(Map<String,String> m:list){
            if(ResourceUtil.FILE_TYPE.equals(m.get("directoryFlag"))){
                m.put("filePath","");
                fileName=m.get("fileName");
                //单页
                if("cover".equals(type)){
                    if(fileName.startsWith("index_")){
                        tList.add(m);
                    }
                }else if("list".equals(type)){
                    if(fileName.equals("list.html") || fileName.startsWith("list_")){
                        tList.add(m);
                    }
                }else if("article".equals(type)){
                    if(fileName.equals("article.html") || fileName.startsWith("article_")){
                        tList.add(m);
                    }
                }else if("special".equals(type)){
                    if(fileName.equals("special.html") || fileName.startsWith("special_")){
                        tList.add(m);
                    }
                }else if("tag".equals(type)){
                    if(fileName.equals("tag.html") || fileName.startsWith("tag_")){
                        tList.add(m);
                    }
                }
            }
        }
        return RespBody.data(tList);
    }


}
